const {ccclass, property} = cc._decorator;

@ccclass
export default class HeroGame extends cc.Component {

    // LIFE-CYCLE CALLBACKS:
    @property(cc.TiledMap)
    tileMap: cc.TiledMap;

    @property(cc.Node)
    dialog: cc.Node;  // 对话框

    onLoad () {
        // getPhysicsManager物理管理器
        let gp:cc.PhysicsManager = cc.director.getPhysicsManager();

        gp.enabled = true;
        // gp.debugDrawFlags = 1;
        // 关闭重力
        gp.gravity = cc.v2(0, 0);

        this.mapInit();

        let dialog = this.dialog.getComponent('dialog');
        dialog.init([
            { role: 2, content: '魔王出场了' },
            { role: 1, content: '勇者出场了' },
            { role: 2, content: '欢迎来到魔王的迷宫，勇者' },
        ]);
    }

    


    mapInit() {
        let tiledSize:cc.Size = this.tileMap.getTileSize();  // 得到小块尺寸

        /*** 通过TileMap组件编写代码，自动生成物理组件作为围墙 ***/
        let layer:cc.TiledLayer = this.tileMap.getLayer("wall");  // 得到墙壁层
        
        let layerSize:cc.Size = layer.getLayerSize();  // 拿到尺寸

        for(let i = 0; i < layerSize.width; i++) {
            for (let j = 0; j < layerSize.height; j++) {   
                let tiled:cc.TiledTile = layer.getTiledTileAt(i, j, true);  // 拿到小块
                // 如果元素存在
                if (tiled.gid != 0) {
                    let body:cc.RigidBody = tiled.node.addComponent(cc.RigidBody);  // 动态添加RigidBody刚体
                    body.type = cc.RigidBodyType.Static;  // 设置为静态，防止下落
                    body.bullet = true;
                    // tiled.node.group = 'wall'; // 将这个节点设置为wall
                    tiled.node.groupIndex = 1;  // 设置节点的groupIndex
                    
                    let collider = tiled.node.addComponent(cc.PhysicsBoxCollider); // 添加碰撞区域
                    
                    collider.offset = cc.v2(tiledSize.width/2, tiledSize.height/2)  // 设置偏移量, 除2是为了拿到中心点
                    collider.size = tiledSize; //包围盒的大小
                    collider.apply();  //回调
                }
            }
        }
    }

    // update (dt) {}
}
